import env from '@/.env.js'

export default {
	config: {
		baseUrl: env.baseUrl,
		data: {},
		method: 'GET',
		dataType: 'json', /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: 'text',
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		return new Promise((resolve, reject) => {
			let _config = null
			options.complete = response => {
						let statusCode = response.statusCode
						response.config = _config
						if (this.interceptor.response) {
							let newResponse = this.interceptor.response(response)
							// (Array.isArray(newResponse) && newResponse.length) || (newResponse && Object.keys(newResponse).length)
					if (newResponse !== false) {
								response = newResponse
							}
						}
						// 统一的响应日志记录
						_reslog(response)
						if (statusCode === 200 ) { //成功
							resolve(response);
						} else {
							reject(response)
						}
				}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}

			// 统一的请求日志记录
			_reqlog(_config)
			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}


/**
 * 请求接口日志记录
 */
function _reqlog(req) {
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {

}

